from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
import this
from flight.models import Itinerary


class EmailVerificationCode(models.Model):
    email_id = models.AutoField(primary_key=True, verbose_name='邮箱号')
    user_id = models.ForeignKey('Users', on_delete=models.CASCADE, verbose_name='用户id', null=True, blank=True)
    captcha = models.CharField(max_length=50, verbose_name='验证码')
    send_time = models.DateTimeField(verbose_name='发送时间')
    session_key = models.CharField(max_length=40, verbose_name='会话ID',null=True, blank=True)  # 添加会话ID字段

    class Meta:
        db_table = 'email_verification_code'  # 数据库名
        verbose_name = '邮箱验证码'  # admin后台展示名称
        verbose_name_plural = verbose_name

    def __str__(self):
        return f"邮箱验证ID {self.email_id}: 用户 {self.user.email if self.user else '无'}"


# 用户信息
class Users(models.Model):
    id = models.AutoField(primary_key=True, verbose_name='用户id')
    email = models.CharField(max_length=255, verbose_name='邮箱')
    password = models.CharField(max_length=255)
    username = models.CharField(max_length=255, verbose_name='用户名', default='momo')

    class Meta:
        db_table = 'user'  # 数据库名
        verbose_name = '用户信息'  # admin后台展示名称
        verbose_name_plural = verbose_name

# 密码加密存储
    def check_password(self, raw_password):
        return check_password(raw_password, self.password)
    def __str__(self):
        return self.email


# 收藏夹
class Favor(models.Model):
    favor_id = models.AutoField(primary_key=True, verbose_name='收藏夹id')
    user = models.ForeignKey('Users', on_delete=models.CASCADE, verbose_name='用户ID', related_name='favors')

    class Meta:
        db_table = 'favor'  # 数据库名
        verbose_name = '收藏夹'  # admin后台展示名称
        verbose_name_plural = verbose_name

    def __str__(self):
        return f"收藏夹ID: {self.favor_id}, 用户: {self.user.email}"


@receiver(post_save, sender=Users)
def create_user_favor(sender, instance, created, **kwargs):
    if created:
        Favor.objects.create(user=instance)


class FavorItinerary(models.Model):
    favor = models.ForeignKey(Favor, on_delete=models.CASCADE, verbose_name='收藏夹', related_name='favor_itineraries')
    itinerary = models.ForeignKey(Itinerary, on_delete=models.CASCADE, verbose_name='航程', related_name='favor_itineraries')
    added_date = models.DateTimeField(auto_now_add=True, verbose_name='添加日期')

    class Meta:
        db_table = 'favor_itinerary'  # 数据库名
        verbose_name = '收藏的航程'  # admin后台展示名称
        verbose_name_plural = verbose_name

    def __str__(self):
        return f"收藏夹: {self.favor.favor_id}, 航程: {self.itinerary.flight_no}"